import { login, getInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import store from '@/store'

const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false,
    menu:[],
    userinfo:{},
    permission:[],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    },
    SET_MENU:(state, menu)=>{
      state.menu = menu
    },
    SET_USERINFO:(state,userinfo)=>{
      state.userinfo = userinfo
    },
    SET_PERMISSION:(state,permission)=>{
      state.permission = permission
    }
  },

  actions: {
    // 登录 done
    Login({ commit }, userInfo) {
      // const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => {
          // setToken(res.token, rememberMe)
          commit('SET_TOKEN', res.token)          
          setToken(res.token)
          getInfo().then(data => {
            // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
            //设置用户信息 目录 权限(给前端判断显示或者隐藏哪些按钮)
            console.log(data,'data')
            commit('SET_LOAD_MENUS', true)
            console.log(store.getters.loadMenus,'loadmenu')
            commit("SET_USERINFO",data.userinfo);
            commit('SET_PERMISSION',data.permission);
            commit('SET_MENU',data.menu);
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息 done
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {          
        getInfo().then(data=>{
            commit('SET_LOAD_MENUS', true)
            commit("SET_USERINFO",data.userinfo);
            commit('SET_PERMISSION',data.permission);
            commit('SET_MENU',data.menu);
            resolve(data)
        }).catch(error=>{
            reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit)
          resolve()
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },

    updateLoadMenus({ commit }) {
      console.log("shenme shihou gaicheng false de")
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false) //表示不需要去构建目录了
      })
    }
  }
}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')  
  commit('SET_LOAD_MENUS', true)
  commit("SET_USERINFO",[]);
  commit('SET_PERMISSION',[]);
  commit('SET_MENU',[]);
  removeToken()
}


export default user
